﻿//#define RESETWARNING

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using ArmoryData;
using Microsoft.Win32;

namespace ArmoryViewerMobile
{

    public partial class Search : Form
    {
        MenuItem searchType;
        List<Dictionary<string, string>> results = new List<Dictionary<string, string>>();
        WarningForm warning = new WarningForm();
        public Search()
        {
            InitializeComponent();
            searchType = mnuCharacters;
        }
        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Keyboard.Enabled = false;
            Cursor.Current = Cursors.WaitCursor;
            lstResults.Items.Clear();
            menuLoad.Enabled = false;
            btnSearch.Enabled = false;
            try
            {
                if(searchType == mnuCharacters)
                        results = Connector.GetSearchResults(new Uri(Program.Settings.ArmoryUrl), txtSearchQuery.Text, "characters");
                else if(searchType == mnuGuilds)
                        results = Connector.GetSearchResults(new Uri(Program.Settings.ArmoryUrl), txtSearchQuery.Text.Replace(" ", "+"), "guilds");
                else if(searchType == mnuArenaTeams)
                        results = Connector.GetSearchResults(new Uri(Program.Settings.ArmoryUrl), txtSearchQuery.Text.Replace(" ", "+"), "arenateams");
                if (results.Count > 0)
                {
                    lstResults.BeginUpdate();
                    lstResults.Items.Clear();
                    FillColumns();
                    foreach (Dictionary<string, string> result in results)
                    {
                        ListViewItem itm = new ListViewItem(result.Values.ToArray<string>());
                        if (!(itm.Text == "No results..."))
                        {
                            lstResults.Items.Add(itm);
                            menuLoad.Enabled = true;
                        }
                        else
                        {
                            MessageBox.Show(itm.Text);
                            menuLoad.Enabled = false;
                        }

                    }
                    lstResults.EndUpdate();
                }
                else
                {
                    menuLoad.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                menuLoad.Enabled = false;
            }

            Cursor.Current = Cursors.Default;
            btnSearch.Enabled = true;
            fixColumnWidth(ref lstResults);
        }

        private void Search_Load(object sender, EventArgs e)
        {
            #if DEBUG
                MinimizeBox = false;
            #else
                MinimizeBox = true;
            #endif

            #if RESETWARNING
                Program.Settings.ShowWarning = true;
            #endif

            btnSearch.Focus();
            menuLoad.Enabled = false;
            FillColumns();

            Program.Settings.Load();

            if (Program.Settings.ConnectOnStartup)
            {
                Cursor.Current = Cursors.WaitCursor;
                Connector.GetHtml(new Uri(Program.Settings.ArmoryUrl));
                Cursor.Current = Cursors.Default;
            }

            //MessageBox.Show(Microsoft.WindowsCE.Forms.SystemSettings.ScreenOrientation.ToString());
            
            //tmrWarning.Enabled = true;
        }

        private void menuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void menuLoad_Click(object sender, EventArgs e)
        {
            Keyboard.Enabled = false;
            if (lstResults.SelectedIndices.Count == 0)
                return;


            int selectedIndex = lstResults.SelectedIndices[0];

          
            ListViewItem selectedItem = lstResults.Items[selectedIndex];
            String name, realm, url;
            name = selectedItem.Text;
            realm = selectedItem.SubItems[6].Text.Replace(" ", "+");
            url = Program.Settings.ArmoryUrl;

            Cursor.Current = Cursors.WaitCursor;
            Profile profile = new Profile();
            if (profile.DownloadInfo(name, realm, url))
            {
                profile.ShowInfo();
                profile.Show();
            }
            Cursor.Current = Cursors.Default;
        }

        private void txtSearchQuery_GotFocus(object sender, EventArgs e)
        {
            tmrFocus.Enabled = true;
            Keyboard.Enabled = true;
        }

        private void txtSearchQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(sender, new EventArgs());
            }
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.Show();
        }

        private void menuPreferences_Click(object sender, EventArgs e)
        {
            PreferencesForm settings = new PreferencesForm();
            settings.Show();
        }

        private void txtSearchQuery_LostFocus(object sender, EventArgs e)
        {
            Keyboard.Enabled = false;
        }

        private void FillColumns()
        {
            ListView x = lstResults;
            x.Columns.Clear();

            if (searchType == mnuCharacters)
            {
                x.Columns.Add(new ColHeader("Name", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Level", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Race", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Class", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Faction", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Guild", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Realm", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Battlegroup", 50, HorizontalAlignment.Left, true));
            }
            else if (searchType == mnuGuilds)
            {
                x.Columns.Add(new ColHeader("Guild", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Realm", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Battlegroup", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Faction", 50, HorizontalAlignment.Left, true));
            }
            else if (searchType == mnuArenaTeams)
            {
                x.Columns.Add(new ColHeader("Team Name", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Realm", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Battlegroup", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Team Type", 50, HorizontalAlignment.Left, true));
                x.Columns.Add(new ColHeader("Faction", 50, HorizontalAlignment.Left, true));
            }
            fixColumnWidth(ref x);
        }

        public static void fixColumnWidth(ref ListView lvw)
        {
            lvw.BeginUpdate();
            foreach (ColumnHeader columnHeader in lvw.Columns)
            {
                columnHeader.Width = -2;
                columnHeader.Width += 10;
            }
            lvw.EndUpdate();
        }

        private void lstResults_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Create an instance of the ColHeader class.
            ColHeader clickedCol = (ColHeader)this.lstResults.Columns[e.Column];

            // Set the ascending property to sort in the opposite order.
            clickedCol.ascending = !clickedCol.ascending;

            // Get the number of items in the list.
            int numItems = this.lstResults.Items.Count;

            // Turn off display while data is repoplulated.
            this.lstResults.BeginUpdate();

            // Populate an ArrayList with a SortWrapper of each list item.
            ArrayList SortArray = new ArrayList();
            for (int i = 0; i < numItems; i++)
            {
                SortArray.Add(new SortWrapper(this.lstResults.Items[i], e.Column));
            }

            // Sort the elements in the ArrayList using a new instance of the SortComparer
            // class. The parameters are the starting index, the length of the range to sort,
            // and the IComparer implementation to use for comparing elements. Note that
            // the IComparer implementation (SortComparer) requires the sort
            // direction for its constructor; true if ascending, othwise false.
            SortArray.Sort(0, SortArray.Count, new SortWrapper.SortComparer(clickedCol.ascending));

            // Clear the list, and repopulate with the sorted items.
            this.lstResults.Items.Clear();
            for (int i = 0; i < numItems; i++)
                this.lstResults.Items.Add(((SortWrapper)SortArray[i]).sortItem);

            // Turn display back on.
            this.lstResults.EndUpdate();
        }

        private void lstResults_ItemActivate(object sender, EventArgs e)
        {
            menuLoad_Click(sender, new EventArgs());
        }

        private void tmrWarning_Tick(object sender, EventArgs e)
        {
            if (Program.Settings.ShowWarning)
            {
                warning.Sender = this;
                warning.Show();
            }
            tmrWarning.Enabled = false;
        }

        private void tmrFocus_Tick(object sender, EventArgs e)
        {
            txtSearchQuery.SelectAll();
            tmrFocus.Enabled = false;
        }

        private void mnuSearchType_Click(object sender, EventArgs e)
        {
            // Uncheck all
            mnuCharacters.Checked = mnuArenaTeams.Checked = mnuGuilds.Checked = false;
            
            // Check clicked item
            MenuItem mnuSender = (MenuItem)sender;
            mnuSender.Checked = true;
            searchType = mnuSender;
        }
    }
}